import mongoose from 'mongoose'

const connection = {}

export async function connectToDatabase() {
  if (connection.isConnected) return

  try {
    const db = await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      dbName: 'nux'
    })

    connection.isConnected = db.connections[0].readyState
  } catch (error) {
    console.error('MongoDB连接失败:', error)
    process.exit(1)
  }
}